package com.testing.sunnycommon.initializer;

import com.testing.sunnycommon.model.SunnyQuartzTask;
import com.testing.sunnycommon.quartz.SunnyQuartzTaskManager;
import com.testing.sunnycommon.service.SunnyQuartzTaskService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Classname TaskInitializer
 * @Description 类型说明
 * @Date 2023/6/21 18:41
 * @Created by 特斯汀Roy
 */
@Component
@Slf4j
public class TaskInitializer implements ApplicationRunner {
    @Autowired
    SunnyQuartzTaskManager sunnyQuartzTaskManager;

    @Autowired
    SunnyQuartzTaskService sunnyQuartzTaskService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<SunnyQuartzTask> sunnyQuartzTasks = sunnyQuartzTaskService.list();
        sunnyQuartzTasks.forEach(task -> {
            //判断定时任务是否是激活状态
            if (task.getIsActive()) {
                try {
                    //如果是启动状态，添加一个定时任务到任务日程表中
                    log.info("开始启动任务" + task);
                    sunnyQuartzTaskManager.activeQuartzTask(task);
                } catch (SchedulerException e) {
                    log.error("启动任务失败" + task, e.fillInStackTrace());
                }
            }
        });
    }
}
